import logging

from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect

from pacp.lib.base import BaseController, render
from pacp import model
from pylons.decorators import jsonify

log = logging.getLogger(__name__)

from pacp.model import detail_flds

from pacp.lib.pipetech import DETAILS

class DetailController(BaseController):
    """REST Controller styled on the Atom Publishing Protocol"""
    # To properly map this controller, ensure your config/routing.py
    # file has a resource setup:
    #     map.resource('detail', 'detail')
    def index(self, format='html'):
        """GET /detail: All items in the collection"""
        try:
            limit = int(request.params['limit'])
        except:
            limit = 25
        try:
            start = int(request.params['start'])
        except:
            start = 0
        try:
            query = int(request.params['query'])
        except:        
            query = None
        if query:
            return self.show(query, limit, start)
        else:
             return self.show(1, limit, start)
       
        

    def create(self):
        """POST /detail: Create a new item"""
        # url('detail')

    def new(self, format='html'):
        """GET /detail/new: Form to create a new item"""
        # url('new_detail')

    def update(self, id):
        """PUT /detail/id: Update an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="PUT" />
        # Or using helpers:
        #    h.form(url('detail', id=ID),
        #           method='put')
        # url('detail', id=ID)

    def delete(self, id):
        """DELETE /detail/id: Delete an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="DELETE" />
        # Or using helpers:
        #    h.form(url('detail', id=ID),
        #           method='delete')
        # url('detail', id=ID)
    @jsonify
    def show(self, id, limit, start, format='html'):
        """GET /detail/id: Show a specific item"""

        q = model.meta.Session.query(model.Details).filter(model.Details.RunID==int(id)).order_by(model.Details.Footage)
        results = []
        for r in q: #q[start:start +limit]: disable limits
             result = {}
             for fld in detail_flds:
                 if DETAILS[fld][0]=='Float':
                    if getattr(r, fld):
                        result[fld] = '%.2f' % getattr(r, fld)
                    else:
                        result[fld] = None
                 else:
                     result[fld] = getattr(r, fld)
             results.append(result)
            
        return {'totalcount': q.count(), 'details': results}

        # url('detail', id=ID)

    def edit(self, id, format='html'):
        """GET /detail/id/edit: Form to edit an existing item"""
        # url('edit_detail', id=ID)
